<?php
namespace core;

/**
 * 常用功能函数
 */
class Func
{

  // 下划线转驼峰
  static function camelize($uncamelized_words,$separator='_'){
      $uncamelized_words = $separator. str_replace($separator, " ", strtolower($uncamelized_words));
      return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator );
  }
  // 驼峰命名转下划线命名
  static function uncamelize($camelCaps,$separator='_'){
      return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
  }
  // 获取thinkphp的当前hash
  static public function getHash(){
    $controller=request()->controller();
    $controller=static::uncamelize($controller);
    $controller=str_replace(".","/",$controller);
    $hash= "/".request()->module()."/".$controller;
    return url($hash,[],"","");
  }
  // 数组转字符串
  static function arr2str($arr,$parm=','){
		$arr=is_array($arr)?implode($parm, $arr):$arr;
		return trim($arr,$parm);
	}
  // 字符串转数组
	static function str2arr($str,$parm=','){
		if (is_string($str) && trim($str)==''){
			$str=array();
		}else{
			$str=is_array($str)?$str:explode($parm,trim($str,$parm));
		}
		return $str;
	}
  // json转数组
	static function json2arr($json){
    $result=[];
    if (!empty($json)){
      if (is_string($json)){
        $result=json_decode($json,true);
        if (empty($result)) $result=[];
      }elseif (is_array($json)) {
        $result=$json;
      }
    }
		return $result;
	}
  // 数组转字符串
	static function arr2json($arr){
    if (empty($arr)) $arr=[];
    if (is_string($arr)) $arr=[$arr];
		return json_encode($arr);
	}
  // 字符串是否以needle开始
  static function startWith($haystack, $needle){
    $length = strlen($needle);
    return (substr($haystack, 0, $length) === $needle);
  }
  // 字符串是否以needle结尾
  static function endWith($haystack, $needle){
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }
    return (substr($haystack, -$length) === $needle);
  }
  // 深层替换数组的数组合并
  static function array_merge_deep(...$arrays){
    $result=array();
    foreach ($arrays as $arr) {
      foreach ($arr as $key => $value) {
        if (isset($result[$key])){
          if ((is_array($result[$key]))&&(is_array($value))){
            $result[$key]=self::array_merge_deep($result[$key],$value);
          }else{
            $result[$key]=$value;
          }
        }else{
          $result[$key]=$value;
        }
      }
    }
    return $result;
  }

}
?>
